import {$$loading} from "plain-ui";

export function persistLoading<V = any>(config?: { onSuccess?: (val: V) => void, onFail?: (val: V) => void }) {
    let ins = null as null | ReturnType<typeof $$loading.bar>
    let status = 'success' as 'success' | 'fail'
    let just = 0
    return {
        start: () => {
            ins = $$loading.bar()
            just = Date.now()
        },
        done: () => {
            const fail = status === 'fail'
            const now = Date.now()
            const dur = now - just
            if (!ins) {return}
            if (dur > 300) {
                !fail ? ins.done() : ins!.fail()
            } else {
                setTimeout(() => !fail ? ins!.done() : ins!.fail(), 300 - dur)
            }
        },
        success: (val: V) => {
            status = 'success'
            !!config && !!config.onSuccess && config.onSuccess(val)
        },
        fail: (val: V) => {
            status = 'fail'
            !!config && !!config.onFail && config.onFail(val)
        },
    }
}
